//
//  ViewController.m
//  Test passenger soldier
//
//  Created by ikuaiyue on 15/7/4.
//  Copyright (c) 2015年 shike. All rights reserved.
//

#import "ViewController.h"
#import "UIDevice+ProcessesAdditions.h"
#import "MyTableViewCell.h"
#import "CurrentData.h"
#import "TimeModel.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "AFNTool.h"
#import "HttpUtil.h"
#import "OpenUDID.h"
#import <AdSupport/AdSupport.h>
#import "UIDevice+IdentifierAddition.h"
#import "SecureUDID.h"
#import "WQUserDataManager.h"
#import "NSString+MD5Addition.h"

//#define mainHttp @"http://www.apptyk.com"
#define mainHttp @"http://112.74.219.188"


@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_tableView;
    NSArray *_dataList;
    NSTimer   *timer;
    NSTimer *_timer;
    NSTimer *_timers;
    NSInteger _Currentnum;
    NSArray *_DataList;
    NSArray *_DataLists;
    NSMutableDictionary *_dicss;
    NSInteger currentTime;
    UIImage *_myHeadImage;
    NSMutableArray *_infoArr;
    
    int count;
    
    int failureCount;
    
    
    NSString * _checktime;
    NSString * _id;
    NSString * _packageName;
    NSString * _protocol;
    NSString * _tryid;
    NSString * _type_id;
    
}

@property (nonatomic, strong)NSString *uid;

@end

@implementation ViewController

- (NSString *)uid
{
    if (_uid) {
        _uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    }
    return _uid;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:NO];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView setBackgroundColor:[UIColor whiteColor]];
//    self.view = _tableView;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];
    imageView.image = [UIImage imageNamed:@"背景图"];
    [self.view addSubview:imageView];
    _Currentnum =0;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 64, 32)];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn setTitle:@"刷新" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(refeshs:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refeshDate:) name:@"refeshDate" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sharedSuccess:) name:@"sharedSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDate:) name:@"getDate" object:nil];
    
//    if (!timer) {
//        timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(updateMeters) userInfo:nil repeats:YES];
//    }
    if (!_timers) {
        _timers = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(updateMeterss) userInfo:nil repeats:YES];
    }
    
    
   UIWebView *_uiwebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, kDeviceWidth, KDeviceHeight -44)];
    _uiwebView.scalesPageToFit = YES;
    _uiwebView.delegate= self;
    _uiwebView.opaque = NO;
    [_uiwebView setBackgroundColor:[UIColor whiteColor]];
//    [self.view addSubview:_uiwebView];
    
//    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://open.weixin.qq.com/connect/qrconnect?appid=wxc828969506b0c397&redirect_uri=http%3A%2F%2Fwww.apptyk.com%2Fdata%2Finfo&response_type=code&scope=snsapi_login&state=state#wechat_redirect"]];
    
//    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf50b93a7184c9e5d&secret=7253c4876b83e409266171c11d580b0c&code=snsapi_base&grant_type=authorization_code"]];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@" https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf50b93a7184c9e5d&redirect_uri=http%3A%2F%2Fwww.apptyk.com%2Fdata%2Finfo&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect"]];
    
   
    
   NSString  *prepayIdUrl = @"sns/oauth2/access_token?appid=wxf50b93a7184c9e5d";
    
    NSMutableDictionary *parames = [NSMutableDictionary dictionary];
    [parames setObject:@"7253c4876b83e409266171c11d580b0c" forKey:@"secret"];
    [parames setObject:@"snsapi_base" forKey:@"code"];
    [parames setObject:@"authorization_code" forKey:@"grant_type"];
    [HttpUtil doGetWithUrl:@"https://api.weixin.qq.com/" path:prepayIdUrl params:parames callback:^(BOOL isSuccessed, NSDictionary *result) {
        LOG(@"%@",result);
    }];
    
    
    
    [_uiwebView loadRequest:request];
    [self initViews];
    
    LOG(@"%@", [[[UIDevice currentDevice]identifierForVendor] UUIDString]);
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
    [_visiblebtn setTitle:@"验证中..." forState:UIControlStateNormal];
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([WQUserDataManager readPassWord]) {
        [dic setObject:[WQUserDataManager readPassWord] forKey:@"deviceid"];
    }
    
        [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/second-check",mainHttp] dic:dic view:nil success:^(id json) {
            LOG(@"%@",json);
            if (![json isKindOfClass:[NSArray class]]) {
                [[NSUserDefaults standardUserDefaults] setObject:json[@"uid"] forKey:@"UID"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                self.uid = json[@"uid"];
                [[NSUserDefaults standardUserDefaults] setObject:json[@"headImgUrl"] forKey:@"headimgurl"];
                if (json[@"url"]) {
                    
                    NSString *url = json[@"url"];
                    LOG(@"%@",url);
                    [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"url"];
                    
                    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
                    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"shared"] integerValue]!=1 && [[NSString stringWithFormat:@"%@",json[@"isUpdate"]] isEqualToString:[infoDic objectForKey:@"CFBundleVersion"]]) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                    }
                    
                }
                [self refeshss:_Currentnum];
                
                if (json[@"accountid"]) {
                    [[NSUserDefaults standardUserDefaults] setObject:json[@"accountid"] forKey:@"accountid"];
                }
                
                [[NSUserDefaults standardUserDefaults] setObject:json[@"nickname"] forKey:@"nickname"];
                [[NSUserDefaults standardUserDefaults] setObject:json[@"unionid"] forKey:@"unionid"];
                
                
                if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
                    [_nameLabel setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"nickname"]];
//                    [_headImageView  setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"headimgurl"]]]]];
//                    [_loginBtn setTitle:@"反还试玩列表" forState:UIControlStateNormal];
//                    [_visiblebtn setTitle:@"已验证" forState:UIControlStateNormal];
                    [_loginBtn setTitle:@"返回粉咖" forState:UIControlStateNormal];
                    [_showBtn setImage:[UIImage imageNamed:@"试玩过程中请保持粉咖后台运行"] forState:UIControlStateNormal];
                    [_visiblebtn setTitle:@"钥匙已激活,让你轻松赚钱" forState:UIControlStateNormal];
                    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
                    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
//                     _buttomLabel.text = [NSString stringWithFormat:@"V%@\nID %@",currentVersion,[[NSUserDefaults standardUserDefaults] objectForKey:@"accountid"]];
                }
                
            }else
            {
                [_visiblebtn setTitle:@"未认证" forState:UIControlStateNormal];
                 [_loginBtn setTitle:@"微信登录认证" forState:UIControlStateNormal];
            }
            LOG(@"%@",json);
            
            
        } failure:^(NSError *error) {
            [_visiblebtn setTitle:@"未认证" forState:UIControlStateNormal];
             [_loginBtn setTitle:@"微信登录认证" forState:UIControlStateNormal];
        }];
        
        
//    }
//    else
//    {
//        NSString * _URL= [[NSUserDefaults standardUserDefaults] objectForKey:@"url"];
//        if (_URL) {
//             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_URL]];
//        }
//       
//    }
   
}
-(void)initViews
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(kDeviceWidth/2-70, 110, 140, 88)];
    view.layer.masksToBounds =YES;
    [self.view addSubview:view];
    _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 140, 88)];
    _headImageView.image = [UIImage imageNamed:@"logo"];
    [_headImageView setContentMode: UIViewContentModeScaleAspectFill];
    [view addSubview:_headImageView];
    _nameLabel = [[ZrsLabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view.frame), kDeviceWidth, 40) font:18 color:[UIColor whiteColor] alignment:NSTextAlignmentCenter isNumber:NO];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        [_nameLabel setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"nickname"]];
    }
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] && [[NSUserDefaults standardUserDefaults] objectForKey:@"headimgurl"]) {
//        [_headImageView  setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"headimgurl"]]]]];
//        }
    [self.view addSubview:_nameLabel];
    _nameLabel.hidden = YES;
    _visiblebtn = [[UIButton alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_nameLabel.frame)-20, kDeviceWidth, 18.5)];
    [_visiblebtn setAdjustsImageWhenHighlighted:NO];
    [_visiblebtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [_visiblebtn.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [self.view addSubview:_visiblebtn];
    _loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth/2-60,CGRectGetMaxY(_visiblebtn.frame)+20, 120, 45)];
    [_loginBtn setAdjustsImageWhenHighlighted:NO];
    [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_loginBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    _loginBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    _loginBtn.layer.borderWidth = 2;
    _loginBtn.layer.cornerRadius = 20;
    
    
   
    _showBtn = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth/2 - 121.5, CGRectGetMaxY(_loginBtn.frame)+12, 243, 16)];
    
//    试玩过程中请保持粉咖后台运行
    [_showBtn setImage:[UIImage imageNamed:@"验证时提示"] forState:UIControlStateNormal];
    [self.view addSubview:_showBtn];
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        [_loginBtn setTitle:@"返回粉咖" forState:UIControlStateNormal];
        
        [_visiblebtn setTitle:@"钥匙已激活,让你轻松赚钱" forState:UIControlStateNormal];
        [_showBtn setImage:[UIImage imageNamed:@"试玩过程中请保持粉咖后台运行"] forState:UIControlStateNormal];
        
    }else
    {
        
        [_loginBtn setTitle:@"微信登录认证" forState:UIControlStateNormal];
        [_visiblebtn setTitle:@"未认证" forState:UIControlStateNormal];
    }
    [_loginBtn addTarget:self action:@selector(refeshs:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];
    
//    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, KDeviceHeight-88, kDeviceWidth, 44)];
//    [btn setTitle:@"开启通知权限,实时获取收益情况" forState:UIControlStateNormal];
//    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [self.view addSubview:btn];
    
    
    _buttomLabel = [[ZrsLabel alloc]initWithFrame:CGRectMake(0, KDeviceHeight-44, kDeviceWidth, 44) font:16 color:[UIColor whiteColor] alignment:NSTextAlignmentCenter isNumber:YES];
    
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    _infoArr = [NSMutableArray arrayWithArray:infoDic[@"LSApplicationQueriesSchemes"]];
    [_infoArr addObject:@"222222222"];
    NSMutableDictionary *dicss = [NSMutableDictionary dictionaryWithObject:_infoArr forKey:@"22222"];
    [dicss writeToFile:[[NSBundle mainBundle] pathForResource:@"info" ofType:@"plist"] atomically:YES];
    LOG(@"%@", [[NSBundle mainBundle] pathForResource:@"info" ofType:@"plist"]);
    LOG(@"%@",infoDic[@"LSApplicationQueriesSchemes"]);
     NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        _buttomLabel.text = [NSString stringWithFormat:@"V%@",currentVersion];
    }
    else
    {
        _buttomLabel.text = [NSString stringWithFormat:@"V%@\n",currentVersion];
    }
    
    [self.view addSubview:_buttomLabel];
    [self refeshss:_Currentnum];
}
-(void)getDate:(NSNotification *)node
{
    [self getMaiDataList];
}
-(void)getMaiDataLists
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
    }else
    {
        return;
    }
    
    
    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/received-task",mainHttp] dic:dic view:nil success:^(id json) {
        
        LOG(@"%@",json);
        
        LOG(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]);
        if ([json isKindOfClass:[NSArray class]] && [json count]!=0) {
            _DataLists = [NSArray arrayWithArray:json];
        }
        if (_DataLists.count) {
            
            for (NSDictionary *dic in _DataLists) {
                if (![dic[@"protocol"] isKindOfClass:[NSNull class]]) {
                    if ([self APCheckIfAppInstalled2:dic[@"protocol"]]) {
                        NSMutableDictionary *dics = [NSMutableDictionary dictionary];
                        [dics setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
                        [dics setObject:dic[@"tryid"] forKey:@"tryid"];
                        [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/is-download",mainHttp] dic:dics view:nil success:^(id json) {
                            LOG(@"%@",json);
                            if ([json[0] isEqualToString:@"success"]) {
                                
                            }else
                            {
                                [self repeadSub:dics];
                            }
                        } failure:^(NSError *error) {
                            [self repeadSub:dics];
                        }];
                    }

                }
            }

        }
        
        
    } failure:^(NSError *error) {
        
    }];
    
    
}
-(void)repeadSub:(NSDictionary *)dic
{
    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/is-download",mainHttp] dic:dic view:nil success:^(id json) {
       
            
    } failure:^(NSError *error) {
        
    }];
}
-(void)getMaiDataList
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
//        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
//    }else
//    {
//        return;
//    }
    
    NSString *params = [[NSUserDefaults standardUserDefaults]objectForKey:@"paramsStr"];
    NSArray *arr = [params componentsSeparatedByString:@"&"];
    int y =0;
    NSMutableArray *arr3 = [NSMutableArray array];
    for (NSString *i in arr) {
        NSArray *arr2 = [i componentsSeparatedByString:@"="];
        arr3[y]=arr2;
        y++;
    }
    NSMutableArray *arrDict = [NSMutableArray array];
    for (NSArray *ar in arr3) {
        NSMutableDictionary *dict = [NSMutableDictionary  dictionary];
        NSString *string1 =[ar objectAtIndex:1];
        NSString *string2 = [ar objectAtIndex:0];
        [dict setObject:string1 forKey:string2];
        [arrDict addObject:dict];
    }
    NSLog(@"%@",arrDict);
    
    _dataList = arrDict;
    _DataList = arrDict;
    _DataLists = arrDict;
    
    for (NSDictionary *dict in arrDict) {
        if ([dict objectForKey:@"checktime"]) {
            _checktime  = [dict objectForKey:@"checktime"];
        }
        if ([dict objectForKey:@"id"]) {
            _id  = [dict objectForKey:@"id"];
        }
        if ([dict objectForKey:@"packageName"]) {
            _packageName  = [dict objectForKey:@"packageName"];
        }
        if ([dict objectForKey:@"protocol"]) {
            _protocol  = [dict objectForKey:@"protocol"];
        }
        if ([dict objectForKey:@"tryid"]) {
            _tryid  = [dict objectForKey:@"tryid"];
        }
        if ([dict objectForKey:@"type_id"]) {
            _type_id  = [dict objectForKey:@"type_id"];
        }
    }
    
    
    if (![_protocol isKindOfClass:[NSNull class]]) {
        
        if ([self APCheckIfAppInstalled2:_protocol]){
            
            
            [self checkTimeSuccess:^(BOOL Success) {
                if (Success) {
                    if (!timer) {
                        //                    count = 3;
                        //                    timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(OnceupdateMeters) userInfo:nil repeats:YES];
                        [self OnceupdateMeters];
                    }
                }
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_protocol]];
            }];
            
            

        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"任务未完成" message:@"粉咖提醒您,您的任务未完成" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];
        }

        
  }

    
    // 3 不需要通知服务器
    
//    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/received-task",mainHttp] dic:dic view:nil success:^(id json) {
//        
//        LOG(@"%@",json);
//        
//        LOG(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]);
//        if ([json isKindOfClass:[NSArray class]] && [json count]!=0) {
//            _DataList = [NSArray arrayWithArray:json];
//        }
//        for (NSDictionary *dic in _DataList) {
//            NSData*jsondata = [NSData dataWithContentsOfFile:dic[@"packageName"]];
//            
//            NSString*jsonString = [[NSString alloc]initWithBytes:[jsondata bytes] length:[jsondata length] encoding:NSUTF8StringEncoding];
//            LOG(@"%@", [dic[@"packageName"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
//            if (![dic[@"protocol"] isKindOfClass:[NSNull class]]) {
//                if ([self APCheckIfAppInstalled2:dic[@"protocol"]])
//                {
//                    if (!timer) {
//                        timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(OnceupdateMeters) userInfo:nil repeats:YES];
//                    }
//                }
//                
//                
//          }
//        }
//        
//        
//    } failure:^(NSError *error) {
//        
//    }];
    
   
}
-(void)refeshDate:(NSNotification *)note
{
    _Currentnum = 0;
}
-(void) dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)updateMeterss
{
    [self getMaiDataLists];
}
-(void)OnceupdateMeters
{
    count --;
    if (count <= 0) {
        [timer invalidate];
        timer = nil;
    }
    _Currentnum =5;
    [self Oncerefesh:_Currentnum];
}
-(void)sharedSuccess:(NSNotification *)note
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        
        if (_DataList) {
            if (_DataList.count) {
                
                for (NSDictionary *dics in _DataList) {
                    //                                LOG(@"%@ ===%@",dics[@"packageName"],dict[@"ProcessName"]);
                    if (dics[@"packageName"]) {
                        TimeModel *timemodel = [[TimeModel alloc]init];
                        timemodel.pid = [NSString stringWithFormat:@"%@",dics[@"id"]];
                        timemodel.pname = dics[@"packageName"];
                        
                        NSDateFormatter *dateFormatter3 = [[NSDateFormatter alloc] init];
                        [dateFormatter3 setDateFormat:@"yyyy-MM-dd"];
                        timemodel.pdata = [dateFormatter3 stringFromDate:[NSDate date]];
                        timemodel.palltime = @"0";
                        timemodel.type = @"0";
                        [CurrentData saveData:timemodel];

                    }
                }
                
                
                for (TimeModel *model in [CurrentData fetchAll]) {
                    for (NSDictionary *dics in _DataList) {
                        failureCount = 3;
                            _dicss = [NSMutableDictionary dictionary];
                            [_dicss setObject:[NSNumber numberWithInteger:[dics[@"id"] integerValue]] forKey:@"taskid"];
                            [_dicss setObject:@"1" forKey:@"status"];
                            [_dicss setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
                            [_dicss setObject:_packageName forKey:@"packageName"];
                            [_dicss setObject:[ASIdentifierManager sharedManager].advertisingIdentifier forKey:@"idfa"];
                            [_dicss setObject:[[NSString stringWithFormat:@"pinktry%d",[dics[@"id"] intValue]] stringFromMD5] forKey:@"sign"];
                            //                    LOG(@"%@",_dicss);
                            [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/task-status",mainHttp] dic:_dicss view:nil success:^(id json) {
                                //                        LOG(@"%@",json);
                                failureCount--;
                                if ([json[0] isEqualToString:@"success"]) {
                                    
                                    model.type = @"1";
                                    [CurrentData uptateTypeModel:model];
                                }else
                                {
                                    [self newReshs:_dicss];
                                }
                                
                            } failure:^(NSError *error) {
                                LOG(@"%@",error.localizedDescription);
                            }];
                        }
                    }
                
            }
        }
        
    }else
    {
        return;
    }
    
    if (_DataList.count == 0) {
        return;
    }

}
-(void)Oncerefesh:(NSInteger)num
{
    if (self.uid) {
      
        if (_DataList) {
            if (_DataList.count) {
                
                for (NSDictionary *dics in _DataList) {
                    //                                LOG(@"%@ ===%@",dics[@"packageName"],dict[@"ProcessName"]);
                    if (dics[@"packageName"]) {
                        TimeModel *timemodel = [[TimeModel alloc]init];
                        timemodel.pid = [NSString stringWithFormat:@"%@",dics[@"id"]];
                        timemodel.pname = dics[@"packageName"];
                        
                        NSDateFormatter *dateFormatter3 = [[NSDateFormatter alloc] init];
                        [dateFormatter3 setDateFormat:@"yyyy-MM-dd"];
                        timemodel.pdata = [dateFormatter3 stringFromDate:[NSDate date]];
                        if ([CurrentData fetchAllFriendsFromLocal:timemodel.pname].count) {
                            NSArray *arr  = [CurrentData fetchAllFriendsFromLocal:timemodel.pname];
                            TimeModel *model = arr[0];
                            if ([timemodel.palltime integerValue]<300) {
                                timemodel.palltime = [NSString stringWithFormat:@"%ld",[model.palltime integerValue]+num];
                                [CurrentData uptateModel:timemodel];
                            }
                            
                            
                        }else
                        {
                            timemodel.palltime = @"0";
                            timemodel.type = @"0";
                            [CurrentData saveData:timemodel];
                        }
                        
                    }
                }
             
                for (TimeModel *model in [CurrentData fetchAll]) {
                    for (NSDictionary *dics in _DataList) {
                        
                        if (dics[@"checktime"]) {
                            currentTime = [dics[@"checktime"] integerValue];
                        }else
                        {
                            currentTime = 270;
                        }
                            
                            
                }
                    _dicss = [NSMutableDictionary dictionary];
                    [_dicss setObject:_id forKey:@"taskid"];
                    [_dicss setObject:@"1" forKey:@"status"];
                    [_dicss setObject:self.uid forKey:@"uid"];
                    [_dicss setObject:_packageName forKey:@"packageName"];
                    [_dicss setObject:[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] forKey:@"idfa"];
                    
                    NSString *md5 = [[NSString stringWithFormat:@"pinktry%@%@",_id,[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]] stringFromMD5];
                    [_dicss setObject:md5 forKey:@"sign"];
                    
                    //                    LOG(@"%@",_dicss);
                    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/task-status",mainHttp] dic:_dicss view:nil success:^(id json) {
                        //                        LOG(@"%@",json);
                        if ([json[0] isEqualToString:@"success"]) {
                            
                            model.type = @"1";
                            [CurrentData uptateTypeModel:model];
                        }else
                        {
                            sleep(5);
                            [self newReshs:_dicss];
                        }
                        
                    } failure:^(NSError *error) {
                        LOG(@"%@",error.localizedDescription);
                    }];
                }

                
            }
        }
        
    }else
    {
        return;
    }
    
    if (_DataList.count == 0) {
        return;
    }

}


-(void)updateMeters
{
    _Currentnum =5;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
    }
//    [AFNTool initYaoYue:@"http://www.apptyk.com/api/test" dic:dic view:nil success:^(id json) {
//        LOG(@"%@",json);
//    } failure:^(NSError *error) {
//        
//    }];
    NSLog(@"%ld",_Currentnum);
    [self refesh:_Currentnum];
}
-(void)refeshs:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"微信登录认证"]) {
        SendAuthReq* req =[[SendAuthReq alloc ] init ];

        req.scope = @"snsapi_userinfo,snsapi_base" ;
        req.state = @"123" ;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
    }else
    {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"url"]]];
//        [self APCheckIfAppInstalled2:@"weixin://"];
        
    }
   
    //跳微信
//
    //调支付宝
    
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@“alipay://test“]];
    
//    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"wxd8ce3e4cc12718dd://hellow"]];
}

- (void) checkTimeSuccess:(void(^)(BOOL Success))complete
{
    __block int timeout = timeout = [_checktime intValue];

    if ([_type_id isEqualToString:@"3"]) {
        complete(false);
        return;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer2 = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer2,dispatch_walltime(NULL, 0),2.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer2, ^{
        if(timeout <=0 ){ //倒计时结束，关闭
            dispatch_source_cancel(_timer2);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置 特别注明：UI的改变一定要在主线程中进行
                complete(true);
            });
        }else{
            //            int minutes = timeout / 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer2);
    
}



-(BOOL)APCheckIfAppInstalled2:(NSString *)urlSchemes
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlSchemes]])
    {
        NSLog(@" installed");
        
        return  YES;
    }
    else
    {
        return  NO;
    }
}

-(void)refeshss:(NSInteger)num
{
    _dataList = [[[[UIDevice currentDevice] runningProcesses:num ] reverseObjectEnumerator] allObjects];
    if (_dataList) {
        
    }else
    {
        return;
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:_dataList forKey:@"packages"];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
    }else
    {
        return;
    }
    
    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/task-download",mainHttp] dic:dic view:nil success:^(id json) {
        LOG(@"%@",json);
        
        
        
    } failure:^(NSError *error) {
        LOG(@"%@",error.localizedDescription);
    }];
    
    [_tableView reloadData];
}


-(void)refesh:(NSInteger)num
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        _dataList = [[[[UIDevice currentDevice] runningProcesses:num dataList:_DataList] reverseObjectEnumerator] allObjects];
        if (_dataList) {
            
        }else
        {
            return;
        }
    }else
    {
        return;
    }
    
    if (_DataList.count == 0) {
        return;
    }
    NSMutableArray *_arr = [NSMutableArray array];
//        [_arr addObject:model.pname];
        for (TimeModel *model in _dataList) {
            for (NSDictionary *dics in _DataList) {
                
                if ([model.pname isEqualToString:dics[@"packageName"]]) {
//                    LOG(@"%@",model.pname);
//                    LOG(@"%@",model.palltime);
                }
                if (dics[@"checktime"]) {
                    currentTime = [dics[@"checktime"] integerValue];
                }else
                {
                    currentTime = 270;
                }
                    _dicss = [NSMutableDictionary dictionary];
                    [_dicss setObject:[NSNumber numberWithInteger:[dics[@"id"] integerValue]] forKey:@"taskid"];
                    [_dicss setObject:@"1" forKey:@"status"];
                    [_dicss setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
                NSString *str = [NSString stringWithFormat:@"pinktry%@%@",_id,[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] ];
                NSString *md5 = [str stringFromMD5];
                    [_dicss setObject:md5 forKey:@"sign"];
//                    LOG(@"%@",_dicss);
                    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/task-status",mainHttp] dic:_dicss view:nil success:^(id json) {
//                        LOG(@"%@",json);
                        if ([json[0] isEqualToString:@"success"]) {
                            model.type = @"1";
                            [CurrentData uptateTypeModel:model];
                        }else
                        {
                            [self newReshs:_dicss];
                        }
                        
                    } failure:^(NSError *error) {
                        LOG(@"%@",error.localizedDescription);
                    }];
                }
            
        }

//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [dic setObject:_arr forKey:@"packages"];
//    
//    [AFNTool initYaoYue:[NSString stringWithFormat:@"http://www.apptyk.com/api/task-download?uid=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]] dic:dic view:nil success:^(id json) {
//        LOG(@"%@",json);
//        
//        
//        
//    } failure:^(NSError *error) {
//        LOG(@"%@",error.localizedDescription);
//    }];
//
//    [_tableView reloadData];
}
-(void)newReshs:(NSMutableDictionary *)dic
{
    
    [dic setObject:self.uid forKey:@"uid"];
    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/task-status",mainHttp] dic:dic view:nil success:^(id json) {
        LOG(@"%@",json);
        failureCount--;
        if ([json[0] isEqualToString:@"success"]) {
            
        }else
        {
            if (failureCount <= 0) {
                return;
            }
            sleep(5);
            [self newReshs:_dicss];
        }
        
    } failure:^(NSError *error) {
        LOG(@"%@",error.localizedDescription);
    }];

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 88;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"MYCELL";
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.model = _dataList[indexPath.row];
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
